var express = require('express')
var router = express.Router()
var fs = require('fs')
var util = require('./util/util')
var url = require('url')
var db = require('./db/db')
var schema = require('./db/schema')
var mongoose = require('mongoose')
var crypto = require('crypto')
var https = require('https')

const TARGET = process.env.npm_lifecycle_event;
const remote = TARGET==='dev' ? '119.29.24.171' : 'localhost'
console.log(remote);
db.connect('mongodb://pan:Siemenlon123@'+remote+'/pan-xzb-xunlei-com')

/**
 * @swagger
 * definition:
 *    tagObjectTemplate:
 *      type: object
 *      properties:
 *        id:
 *          type: number
 *          description: 类型ID，ID=1表示最近
 *          default: 1
 *    tagTypeObject:
 *      type: object
 *      properties:
 *        id:
 *          type: number
 *          description: 标签类型,1:保存到下载宝，2：保存到手机
 *          default: 1
 *    tagObject:
 *      type: object
 *      properties:
 *        tagTypeObject:
 *          schema:
 *            $ref: '#/definitions/tagTypeObject'
 *        tagDateTime:
 *          type: string
 *          description: 标签创建时间戳
 *        tagPath:
 *          type: string
 *          description: 文件路径
 *    tagObjectForCreate:
 *      type: object
 *      properties:
 *        tagObject:
 *          schema:
 *            $ref: '#/definitions/tagObjectTemplate'
 *        tagTypeObject:
 *          schema:
 *            $ref: '#/definitions/tagTypeObject'
 *        tagPath:
 *          type: string
 *          description: 文件路径
 *        userID:
 *          type: string
 *          description: 用户ID
 *        deviceID:
 *          type: string
 *          description: 设备ID
 * /api/transform:
 *   get:
 *     tags:
 *       - transform
 *     parameters:
 *       - name: fileurl
 *         in: query
 *         description: 文件远场url
 *         required: true
 *         type: string
 *         format: double,
 *     description: 转换office文档
 *     produces:
 *       - text/html
 *     responses:
 *       200:
 *         description: html文件流
 */
router.get('/transform', function(req, res, next) {
  var query = req.query
  if(query.fileurl){
    const file_url = encodeURI(query.fileurl)
    let extName = /.*\/.*(\..*)$/i.exec(url.parse(file_url).pathname)
    if(extName){
      extName = extName[1]
    }

    let request = require('request');
    //let fileContent = '';

    const fileName = './cachedfile/'+new Date()*1 + Math.random();
    const ws = fs.createWriteStream(fileName + extName)

    const fileStream = request(file_url).on('response',function(response) {
        // response.on('data', function(data) {
        //   // compressed data as it is received
        //   fileContent += data;
        // })
    }).on('error',function(err){
      console.log(err)
      util.jsonRespond(res,{
        msg:'文件下载错误',
        code:102
      },{
        status:500
      })
    }).pipe(ws)

    ws.on('finish',function(){
      var unoconv = require('unoconv')
        //
        // const crypto = require('crypto');
        // const secret = 'pan.xzb.xunlei.com';
        // const hash = crypto.createHmac('sha1', secret)
        //                    .update(fileContent)
        //                    .digest('hex');
        //全文hash
      	unoconv.convert(fileName + extName, 'html', function (err, result) {
          // result is returned as a Buffer
          if(!err){
            fs.exists(fileName + '.html', (exists) => {
              if(exists){
                fs.createReadStream(fileName + '.html').pipe(res)
              }
              else{
                util.jsonRespond(res,{
                  msg:'文件转换错误',
                  code:100
                },{
                  status:500
                })
              }
            });
          }
          else{
            console.log(err)
            util.jsonRespond(res,{
              msg:'文件转换错误',
              code:101
            },{
              status:500
            })
          }
      })

    })
  }
  else{
    util.jsonRespond(res,{
      msg:'no fileurl',
      code:400
    },{
      status:400
    })
  }
})

router.get('/htmldoc/:cid',function(req,res,next){
    var Htmldoc = mongoose.model('htmldoc', schema.htmldocSchema);
    Htmldoc.findOne({
        cid: req.params.cid
    }, 'htmlContent', function(err, htmldoc){
        if(err){
            util.jsonRespond(res,{
              msg:err,
              code:500
            },{
              status:500
            })
        }
        else{
            if(htmldoc){
                res.write(htmldoc.htmlContent)
                res.end()
            }
            else{
                util.jsonRespond(res,{
                  msg:'no htmldoc',
                  code:204
                },{
                  status:204
                })
            }
        }
    })
})
/**
 * @swagger
 * /api/tags/{tagObjectId}:
 *   get:
 *     tags:
 *       - tags
 *     parameters:
 *       - name: tagObjectId
 *         in: path
 *         description: tagObjectId
 *         required: true
 *         type: integer
 *       - name: userid
 *         in: query
 *         description: userid
 *         required: true
 *         type: string
 *       - name: deviceid
 *         in: query
 *         description: deviceid
 *         required: true
 *         type: string
 *       - name: skip
 *         in: query
 *         description: skip
 *         required: true
 *         type: integer
 *       - name: limit
 *         in: query
 *         description: limit
 *         required: true
 *         type: integer
 *       - name: daystart
 *         in: query
 *         description: '2016-08-20'
 *         required: true
 *         type: string
 *       - name: dayend
 *         in: query
 *         description: '2016-08-21'
 *         required: true
 *         type: stringr
 *     description: 获取对应类型的tag的文件列表,1表示最近文件列表
 *     produces:
 *       - application/json
 *     responses:
 *       200:
 *         description: 文件列表
 *         schema:
 *            items:
 *               type: array
 *               $ref: '#/definitions/tagObject'
 */
//getTag
router.get('/tags/:tagObjectId?',function(req,res,next){
    var Tag = mongoose.model('tag', schema.tagSchema);
    var promiseArray = []
    var days = (new Date(req.query.dayend) - new Date(req.query.daystart)) / 86400000

    for(var i=0;i<=days;i++){
        var startDate = new Date(req.query.daystart);
        startDate.setDate(startDate.getDate()+i);
        var endDate = new Date(startDate);
        endDate.setDate(endDate.getDate()+1);

        var query = {
          userID:req.query.userid?req.query.userid:'',
          deviceID:req.query.deviceid?req.query.deviceid:'',
          tagDateTime:{$gt: startDate, $lt: endDate}
        }
        if(req.params.tagObjectId){
            query.tagObject = {id:req.params.tagObjectId*1}
        }

        var countPromise = new Promise(function(resolve, reject) {
            Tag.count(query).exec(function(err, count){
                if(err){
                    reject({
                      err: err,
                      msg:'err',
                      code:501
                    },{
                      status:500
                    })
                }
                else {
                    resolve(count)
                }
            });
        });
        var arrayPromise = new Promise(function(resolve, reject) {
            Tag.find(query, {_id:false,tagPath:true,tagTypeObject:true,tagDateTime:true})
            .skip(req.query.skip?req.query.skip*1:0)
            .limit(req.query.limit?req.query.limit*1:10000)
            .sort({'tagDateTime':-1})
            .exec(function(err, tags){
                if(err){
                    reject({
                      err: err,
                      msg:'err',
                      code:502
                    },{
                      status:500
                    })
                }else{
                    if(tags){
                      resolve(tags)
                    }else{
                        reject({
                          msg:'no tags',
                          code:404
                        },{
                          status:404
                        })
                    }
                }
            })
        });
        promiseArray.push(arrayPromise)
        promiseArray.push(countPromise)
    }

    Promise.all(promiseArray).then(function(values){
        var result = [];
        for(var i=0;i<values.length;i+=2){
            result.push({
                list:values[i],
                count:values[i+1]
            })
        }
        util.jsonRespond(res,{
          data:result,
          msg:'',
          code:200
        },{
          status:200
        })
    }).catch(function(errs){
        console.log(errs)
        util.jsonRespond(res,{
          msg:'get error',
          code:500
        },{
          status:500
        })
    })
})

/**
 * @swagger
 * /api/tags:
 *   post:
 *     tags:
 *       - tags
 *     parameters:
 *       - name: tag
 *         in: body
 *         required: true
 *         schema:
 *            $ref: '#/definitions/tagObjectForCreate'
 *     description: 新增一条最近记录
 *     produces:
 *       - application/json
 *     responses:
 *       201:
 *         description: 记录创建成功
 *       500:
 *          description: code=501 userID或者deviceID不存在，code=502、500 新增失败
 */
router.post('/tags',function(req,res,next){
    var Tag = mongoose.model('tag', schema.tagSchema);
    //数据校验
    if(!req.body.userID || !req.body.deviceID){
      util.jsonRespond(res,{
        msg:'userID or deviceID missing',
        code:501
      },{
        status:500
      })
      return;
    }
    Tag.create({
        tagObject:req.body.tagObject,
        tagPath:req.body.tagPath,
        tagTypeObject:req.body.tagTypeObject,
        tagDateTime:new Date(),
        userID:req.body.userID,
        deviceID:req.body.deviceID
    }, function(err, tag) {
        if(err){
            util.jsonRespond(res,{
              msg:err,
              code:500
            },{
              status:500
            })
        }
        else{
            if(tag){
                util.jsonRespond(res,{
                  msg:'add success',
                  code:201
                },{
                  status:201
                })
            }
            else{
                util.jsonRespond(res,{
                  msg:'add failed',
                  code:502
                },{
                  status:500
                })
            }
        }
    });
});


/**
 * @swagger
 * /api/tags:
 *   delete:
 *     tags:
 *       - tags
 *     parameters:
 *       - name: tagpath
 *         in: query
 *         description: tagPath
 *         required: true
 *         type: string
 *         format: text/html
 *       - name: tagtypeobjectid
 *         in: query
 *         required: true
 *         description: tagtypeobjectid
 *         type: string
 *       - name: userid
 *         in: query
 *         description: userID
 *         required: true
 *         type: string
 *       - name: deviceid
 *         in: query
 *         description: deviceID
 *         required: true
 *         type: string
 *     description: 删除一条最近记录
 *     produces:
 *       - application/json
 *     responses:
 *       200:
 *         description: 删除成功
 *       500:
 *         description: 删除失败
 *       400:
 *         description:无记录
 */
router.delete('/tags',function(req,res,next){
    var Tag = mongoose.model('tag', schema.tagSchema);
    var query = {
      userID:req.query.userid?req.query.userid:'',
      deviceID:req.query.deviceid?req.query.deviceid:'',
      tagPath:req.query.tagpath
    };
    if(req.query.tagtypeobjectid){
      query['tagTypeObject.id'] = req.query.tagtypeobjectid * 1
    }
    console.log(query)
    Tag.findOneAndRemove(query, function(err, tag) {
        if(err){
            util.jsonRespond(res,{
              msg:err,
              code:500
            },{
              status:500
            })
        }
        else{
            if(tag){
                util.jsonRespond(res,{
                  msg:'delete success',
                  code:200
                },{
                  status:200
                })
            }
            else{
                util.jsonRespond(res,{
                  msg:'no tag to delete',
                  code:404
                },{
                  status:404
                })
            }
        }
    });
});


/**
 * @swagger
 * /api/tags:
 *   put:
 *     tags:
 *       - tags
 *     parameters:
 *       - name: tagpath
 *         in: query
 *         description: tagPath
 *         required: true
 *         type: string
 *       - name: userid
 *         in: query
 *         description: userID
 *         required: true
 *         type: string
 *       - name: deviceid
 *         in: query
 *         description: deviceID
 *         required: true
 *         type: string
 *       - name: tagobjectid
 *         in: query
 *         required: true
 *         description: tagobjectid
 *         type: string
 *       - name: tagtypeobjectid
 *         in: query
 *         required: true
 *         description: tagtypeobjectid
 *         type: string
 *       - name: tag
 *         in: body
 *         required: true
 *         schema:
 *            $ref: '#/definitions/tagObjectForCreate'
 *     description: 更新一条最近记录
 *     produces:
 *       - application/json
 *     responses:
 *       200:
 *         description: 更新记录成功
 *       500:
 *         description: 更新记录失败
 *       404:
 *         description: 未找到记录
 */
router.put('/tags',function(req,res,next){
    var Tag = mongoose.model('tag', schema.tagSchema);
    var query = {
      userID:req.query.userid?req.query.userid:'',
      deviceID:req.query.deviceid?req.query.deviceid:'',
      tagPath:req.query.tagpath,
      tagObject:{id:req.query.tagobjectid*1},
      tagTypeObject:{id:req.query.tagtypeobjectid*1}
    };

    console.log(query)
    Tag.findOneAndUpdate(query,{
      tagObject:req.body.tagObject,
      tagTypeObject:req.body.tagTypeObject,
      tagPath:req.body.tagPath
    }, function(err, tag) {
        if(err){
            util.jsonRespond(res,{
              msg:err,
              code:500
            },{
              status:500
            })
        }
        else{
            if(tag){
                util.jsonRespond(res,{
                  msg:'update success',
                  code:200
                },{
                  status:200
                })
            }
            else{
                util.jsonRespond(res,{
                  msg:'no tag to delete',
                  code:404
                },{
                  status:404
                })
            }
        }
    });
});


module.exports = router;
